package br.com.kitnet.sample.conexaobd;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import org.springframework.jdbc.core.RowMapper;

public abstract class AbstractRowMapper implements RowMapper {

	/** Invalid Column Name SQLCode */
	public static final String INVALID_COLUMN_NAME = "07009";

	/**
	 * Read the resultset and return the value if there's a columns with the
	 * specified name
	 * 
	 * @param <T>
	 * @param rs
	 * @param clazz
	 * @param columnName
	 * @return ResultSet value
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public <T> T getValue(ResultSet rs, Class<T> clazz, String columnName)
			throws SQLException {

		Object returnValue = null;

		try {

			if (clazz.equals(BigDecimal.class)) {
				returnValue = rs.getBigDecimal(columnName);

			} else if (clazz.equals(Boolean.class)) {
				returnValue = rs.getBoolean(columnName);

			} else if (clazz.equals(Date.class)) {
				returnValue = rs.getTimestamp(columnName);

			} else if (clazz.equals(Double.class)) {
				returnValue = rs.getDouble(columnName);

			} else if (clazz.equals(Integer.class)) {
				returnValue = rs.getInt(columnName);

			} else if (clazz.equals(Long.class)) {
				returnValue = rs.getLong(columnName);

			} else if (clazz.equals(String.class)) {
				returnValue = rs.getString(columnName);

			}

			if (rs.wasNull()) {
				returnValue = null;
			}

		} catch (SQLException e) {
			// If the SQLCode is 07009 so there's no column with the specified
			// name then the return should be null
			if (e.getSQLState() != null) {
				if (!e.getSQLState().equals(INVALID_COLUMN_NAME)) {
					throw e;
				}
			} else {
				throw e;
			}
		}

		return (T) returnValue;

	}
}
